<template>
  <div class="container">
    <!-- 查询配置 -->
    <div style="padding: 0px 20px">
      <div ref="lxHeader">
        <LxHeader icon="md-apps" text="安全生产目标" style="margin-bottom: 10px; border: 0px; margin-top: 15px">
          <div slot="content"></div>
          <slot>
            <div>
              <Input style="width: 200px; margin-right: 10px" v-model="searchFields.KeyWord" placeholder="关键字搜索" />
              <Button type="primary" @click="load" style="margin-left: 10px">查询</Button>
              <Button type="primary" @click="edit()" style="margin-left: 10px">新增</Button>
            </div>
          </slot>
        </LxHeader>
      </div>
      <div ref="lxTable">
        <el-table :data="tableData" class="v-table" :height="tableHeight" style="width: 100%">
          <el-table-column type="index" width="50" align="center" fixed="left"> </el-table-column>
          <el-table-column :prop="column.field" :align="column.align" v-for="(column,index) in columns"
            :label="column.title" :width="column.width" :fixed="column.fixed">
            <template slot-scope="scope">
              <div v-if="column.type=='opt'">
                <Button ghost size="small" @click="check(scope.row)" type="primary"
                  style="margin-left: 10px;">检查</Button>
                <Button ghost size="small" @click="edit(scope.row)" type="primary"
                  style="margin-left: 10px;">编辑</Button>
                <Button ghost size="small" @click="del(scope.row)" type="error" style="margin-left: 10px;">删除</Button>
              </div>
              <div v-else-if="column.type=='department_id'">
                <div v-for="dep in deptOptions">
                  <div v-if='scope.row[column.field]==dep.id'>
                    {{dep.name}}
                  </div>
                </div>

              </div>
              <div v-else-if="column.type=='quarter'">
                <div v-for="quarter in quarters">
                  <div v-if='scope.row[column.field]==quarter.id'>
                    {{quarter.value}}
                  </div>
                </div>

              </div>
              <div v-else-if="column.field=='checks_count'">
                <el-tag :type="scope.row[column.field]==0?'warning':''" v-html="scope.row[column.field]==0?'否':'是'"></el-tag>
              </div>
              <div v-else-if="column.type=='format'">
                <div v-if="column.field=='admin' || column.field=='department'">
                  {{scope.row[column.field]?scope.row[column.field].name:""}}
                </div>
              </div>
              <div v-else>{{scope.row[column.field]}}</div>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination @current-change="handleCurrentChange" :current-page="paginations.page"
            :page-size="paginations.page_size" background layout="prev, pager, next" :total="paginations.total">
          </el-pagination>
        </div>
      </div>
    </div>

    <el-dialog title="安全生产目标编辑" :visible.sync="dialogFormVisible" fullscreen width="90%">
      <div class="dialogConcent" :style="{height:clientHeight+'px'}">
        <el-scrollbar style="flex: 1">
          <el-form :model="form" :rules="rules" ref="form" label-position="right" :label-width="formLabelWidth">
            <el-row>
              <el-col :span="8">
                <el-form-item label="选择年份" prop="year" label-position="right">
                  <el-date-picker style="width:100%" placeholder="选择年份" type="year" v-model="form.year" format="yyyy" value-format="yyyy">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="8">
                <el-form-item class="" label="季度" prop="quarter" label-position="right">
                  <el-select v-model="form.quarter" placeholder="请选择季度" style="width: 100%">
                    <el-option v-for="item in quarters" :key="item.id" :label="item.value" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item class="longtext" label="备注" prop="remark">
              <el-input type="textarea" :rows="3" v-model="form.remark" placeholder="请填写备注" autocomplete="off">
              </el-input>
            </el-form-item>
            <el-form-item label="附件" prop="file_list" class="target_files">
              <el-upload class="upload-demo" :on-success="handlesuccess" :data="uploadOther"
                :action="action" :on-remove="handleRemove" :before-remove="beforeRemove"
                :on-exceed="handleExceed" :file-list="fileList">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
            <div style="padding: 20px 0px;" class="form-sub-title">
              <span>详细信息
              </span>
            </div>
            <div class="table-tree tableswidth">
              <div style="display: flex;justify-content: flex-end;margin-right: 20px;margin-bottom: 10px;">
                <Button type="primary" @click="addRow()" size="small" style="margin-left: 10px;" ghost>新增</Button>
              </div>
              <el-table :data="form.details_list" height="400" class="v-table"
                style="width: 100%;margin-bottom: 20px;">
                <el-table-column type="index" align="center">
                </el-table-column>
                <el-table-column prop="target" label="安全生产目标,指标" width="320px">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.target" />
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" width="">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.remark" />
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="220px" align="center">
                  <template slot-scope="scope">
                    <Button type="error" @click="delRow('',scope.$index)" size="small" style="margin-left: 10px;"
                      ghost>删除</Button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form>
        </el-scrollbar>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('form')">取 消</el-button>
        <el-button type="primary" v-preventReClick @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="安全生产目标检查编辑" :visible.sync="dialogCheckFormVisible" fullscreen width="90%">
      <div class="dialogConcent" :style="{height:clientHeight+'px'}">
        <el-scrollbar style="flex: 1">
          <el-form :model="check_form" :rules="checkrules" ref="check_form" label-position="right"
            :label-width="formLabelWidth">
            <el-row>
              <el-col :span="8">
                <el-form-item label="检查科室" prop="department_id" label-position="right">
                  <el-select v-model="check_form.department_id" placeholder="请选择检查科室" style="width: 100%">
                    <el-option v-for="item in deptOptions" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="8">
                <el-form-item class="" label="检查日期" prop="date" label-position="right">
                  <el-date-picker style="width:100%" type="date" v-model="check_form.date" value-format="yyyy-MM-dd HH:mm:ss">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item class="longtext" label="备注" prop="remark">
              <el-input type="textarea" :rows="3" v-model="check_form.remark" placeholder="请填写备注" autocomplete="off">
              </el-input>
            </el-form-item>
            <el-form-item label="附件" prop="file_list" class="target_files">
              <el-upload class="upload-demo" :on-success="handlesuccess" :data="uploadOther"
                :action="action" :on-remove="handleRemove" :before-remove="beforeRemove"
                :on-exceed="handleExceed" :file-list="checkFileList">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
            <div style="padding: 20px 0px;" class="form-sub-title">
              <span>详细信息
              </span>
            </div>
            <div class="table-tree tableswidth">
              <div style="display: flex;justify-content: flex-end;margin-right: 20px;margin-bottom: 10px;">
                <Button type="primary" @click="addRow('check')" size="small" style="margin-left: 10px;"
                  ghost>新增</Button>
              </div>
              <el-table :data="check_form.details_list" height="400" class="v-table"
                style="width: 100%;margin-bottom: 20px;">
                <el-table-column type="index" align="center">
                </el-table-column>
                <el-table-column prop="target" label="安全生产目标,指标" width="320px">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.target" />
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.remark" />
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="result" label="检查评估结果" width="580px">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.result" />
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120px" align="center">
                  <template slot-scope="scope">
                    <Button type="error" @click="delRow('check',scope.$index)" size="small" style="margin-left: 10px;"
                      ghost>删除</Button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form>
        </el-scrollbar>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('check_form')">取 消</el-button>
        <el-button type="primary" v-preventReClick @click="submitCheckForm('check_form')">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
  import {
    getToken
  } from '@/utils/auth'
  import LxHeader from "@/components/LxHeader/index.vue";
  import Tinymce from '@/components/Tinymce'
  import {
    save,
    store,
    del,
    get,
    listtask,
    checksave
  } from "../../api/objective/target.js";
  import {
    listdept
  } from "../../api/system/department.js";
  export default {
    components: {
      LxHeader,
      Tinymce
    },
    data() {
      return {      action:`${process.env.VUE_APP_BASE_API}api/admin/upload-file`,
        checkAll: false,
        isIndeterminate: true,
        infoFormVisible: false,
        paginations: {
          page: 1,
          page_size: 15,
          total: 0
        },
        tableHeight: 0,
        dialogFormVisible: false,
        dialogCheckFormVisible: false,
        formLabelWidth: "120px",
        clientHeight: 0,
        form: {
          year: "",
          quarter: "",
          remark: "",
          file_list: "",
          details_list: [{
            target: "",
            remark: "",
          }],
        },
        check_form: {
          department_id: "",
          date: "",
          remark: "",
          file_list: "",
          details_list: [{
            target: "",
            remark: "",
            result: ""
          }],
        },
        //查询条件字段
        searchFields: {
          KeyWord: ""
        },
        details_list: [],
        fileList: [],
        checkFileList: [],
        tableData: [],
        rules: {
          year: [{
            required: true,
            message: '请选择年份',
            trigger: 'blur'
          }],
          quarter: [{
            required: true,
            message: '请选择季度',
            trigger: 'blur'
          }],
          remark: [{
            message: '请填写备注',
            trigger: 'blur'
          }],
        },
        checkrules: {
          department_id: [{
            required: true,
            message: '请选择科室',
            trigger: 'blur'
          }],
          date: [{
            required: true,
            message: '请选择发现时间',
            trigger: 'blur'
          }],
          remark: [{
            message: '请填写备注',
            trigger: 'blur'
          }],
        },
        columns: [
          {
            field: "year",
            title: "年份",
            type: "string",
            width: 120,
            align:"left"
          },{
            field: "department_id",
            title: "科室",
            type: "department_id",
            width:120,
            align:"center"
          },
          {
            field: "quarter",
            title: "季度",
            type: "quarter",
            width: 120,
            align:"center"

          },
          {
            field: "remark",
            title: "备注",
            width: 180,
            align:"left"
          },
          {
            field: "checks_count",
            title: "是否已检查",
            type: "checks_count",
            width: 120,
            align:"center"
          },
          {
            field: "created_at",
            title: "创建时间",
            type: "string",
            width: 180,
            align: "center"
          },
          {
            field: "admin",
            title: "创建人",
            type: "format",
            width: 120,
            align: "center"
          },
          {
            field: "department",
            title: "创建人科室",
            type: "format",
            width: 120,
            align: "center"
          },
          {
            field: "操作",
            title: "操作",
            width: 220,
            type: "opt",
            fixed:'right'
          }
        ],
        quarters: [{
          id: 1,
          value: "第一季度"
        }, {
          id: 2,
          value: "第二季度"
        }, {
          id: 3,
          value: "第三季度"
        }, {
          id: 4,
          value: "第四季度"
        }],
        uploadOther: {
          token: ""
        },
        deptOptions: []
      }

    },
    created() {
      this.uploadOther.token = getToken();
      this.loadDeptOptions();
      this.initLoad();
      this.load();

    },
    methods: {
      loadDeptOptions() {
        listdept().
        then((res) => {
          this.deptOptions = res;
        }).catch(error => {
          console.log(error)
          reject(error)
        })
      },
      addRow(check) {
        var len = this.form.details_list.length;
        if (check) {
          this.check_form.details_list.push({
            target: "",
            remark: "",
          });
        } else {
          this.form.details_list.push({
            target: "",
            remark: "",
            result: ""
          });
        }
      },
      delRow(check, index) {
        if (check != "") {
          this.check_form.details_list.splice(index, 1);
        } else {
          this.form.details_list.splice(index, 1);
        }

      },
      initLoad() {
        var that = this;
        var clientHeight = document.documentElement.clientHeight
        var lxHeader_height = 96.5; //查询 头部
        var paginationHeight = 37; //分页的高度
        var topHeight = 50; //页面 头部
        let tableHeight = clientHeight - lxHeader_height - topHeight - paginationHeight - 20;
        that.tableHeight = tableHeight;
      },
      handleCurrentChange(page) {
        this.paginations.page = page;
        this.load();
      },
      load() {
        listtask({
          page: this.paginations.page,
          page_size: this.paginations.page_size,
          keyword:this.searchFields.KeyWord
        }).then(response => {
          this.tableData = response.data;
          this.paginations.total = response.total;
        }).catch(error => {
          console.log(error)
          reject(error)
        })

      },
      del(obj) {
        var that = this;
        if (obj) {
          this.$Modal.confirm({
            title: '确认要删除数据？',
            onOk: () => {
              del(obj.id).then(response => {
                this.$Message.success('操作成功');
                that.load();
              }).catch(error => {
                console.log(error)
                reject(error)
              })
            },
            onCancel: () => {
              //this.$Message.info('Clicked cancel');
            }
          });
        }
      },
      info(obj) {
        var that = this;
        var copydetails = [];
        get(obj.id).then(res => {
          let result = Object.assign(that.form, res);
          that.form = result;
          let _files = [];
          let _checkfiles = [];
          for (var mod of result.safety_target_files) {
            let m = Object.assign({}, mod["files"]);
            m.name = mod["files"].original_name;
            _files.push(m);
          }
          for (var mod of result.checks.safety_target_check_files) {
            let m = Object.assign({}, mod["files"]);
            m.name = mod["files"].original_name;
            _checkfiles.push(m);
          }
          that.check_form = result.checks;
          that.fileList = _files;
          that.checkFileList = _checkfiles;
          copydetails = result.details;
          that.form.details_list = copydetails;
          that.check_form.details_list = copydetails;
          for (var i = 0; i < that.check_form.details_list.length; i++) {
            this.$delete(that.check_form.details_list[i], 'safety_target_id');
            this.$delete(that.check_form.details_list[i], 'id');
          }
          that.form.year = result.year.toString();
        }).catch(error => {
          //reject(error)
        })
      },
      edit(obj) {
        this.form = this.$options.data().form;
        this.clientHeight = document.documentElement.clientHeight - 84 - 110;
        if (obj) {
          var that = this;
          that.info(obj);
        } else {}
        this.dialogFormVisible = true;
      },
      check(obj) {
        this.form = this.$options.data().form;
        this.clientHeight = document.documentElement.clientHeight - 84 - 110;
        if (obj) {
          var that = this;
          that.info(obj);
        } else {}
        this.dialogCheckFormVisible = true;
      },

      submitForm(formName) {
        var that = this;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (that.form.id) {
              that.form.id = that.form.id;
              save(that.form).then(response => {
                //console.log(response)
                this.$Message.success('操作成功');
                that.load();
                that.dialogFormVisible = false;
              }).catch(error => {
                //reject(error)
              })

            } else {
              store(that.form).then(response => {
                //console.log(response)
                this.$Message.success('操作成功');
                that.load();
                that.dialogFormVisible = false;
              }).catch(error => {
                //reject(error)
              })
            }
          } else {
            this.$Message.error('数据校验失败');
            console.log('error submit!!');
            return false;
          }
        });
      },
      submitCheckForm(formName) {
        var that = this;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (that.form.id) {
              that.check_form.id = that.form.id;
              checksave(that.check_form).then(response => {
                //console.log(response)
                this.$Message.success('操作成功');
                that.load();
                that.dialogCheckFormVisible = false;
              }).catch(error => {
                //reject(error)
              })
            }
          } else {
            this.$Message.error('数据校验失败');
            console.log('error submit!!');
            return false;
          }
        });
      },
      handleRemove(file, fileList) {
        let listUrl = [];
        for (var m of fileList) {
          if (m.response)
            listUrl.push({
              "upload_id": m.response.id
            });
          else
            listUrl.push({
              "upload_id": m.id
            });
        }
        if (this.dialogFormVisible) {
          this.form.file_list = listUrl;
        } else if (this.dialogCheckFormVisible) {
          this.check_form.file_list = listUrl;
        }


      },
      handleExceed(files, fileList) {},
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      handlesuccess(response, file, fileList) {
        let listUrl = [];
        for (var m of fileList) {
          if (m.response)
            listUrl.push({
              "upload_id": m.response.id
            });
          else
            listUrl.push({
              "upload_id": m.id
            });
        }
        if (this.dialogFormVisible) {
          this.form.file_list = listUrl;
        } else if (this.dialogCheckFormVisible) {
          this.check_form.file_list = listUrl;
        }
      },
      resetForm(formName) {
        var that = this;
        this.$refs[formName].resetFields();
        that.fileList = [];
        that.checkFileList = [];
        that.dialogFormVisible = false;
        that.dialogCheckFormVisible = false;
      },
    }
  }
</script>

<style>
  .dialogConcent {
    overflow-y: auto;
  }

  .longtext {
    margin-left: 43px;
  }

  .longtext label {
    float: none;
    text-align: left;
  }

  .longtext .el-form-item__content {
    margin-left: 0 !important;
    width: 100%;
  }

  .tableswidth table.el-table__header {
    width: 100% !important;
  }

  .target_files label {
    width: 84px !important
  }

  .target_files .el-form-item__content {
    margin-left: 83px !important
  }
</style>
