<template>
  <DragModal
      :title="$t('measure-track.measure-track.edit')"
      :visible="dialogFormVisible"
      :width="1000"
      :destroyOnClose="true"
      @cancel="closeModal">
    <div>
      <div>
        <a-form v-bind='formItemLayout'>
          <a-form-item required :label="$t('measure-track.measure-track.status')">
            <a-select @change="stateChange" :value="state">
              <a-select-option
                  v-for="(item, index) in stateDict"
                  :key="index"
                  :value="item.value">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item required :label="$t('measure-track.measure-track.plan-date')">
            <a-date-picker
                class="width100"
                :value="planDate"
                valueFormat="YYYY-MM-DD"
                :allowClear="false"
                @change="planDateChange"/>
          </a-form-item>
        </a-form>
      </div>
      <div class="mt10">
        <a-table
            :title="()=> {return $t('measure-track.measure-track.responsible-person')}"
            :data-source="tableData"
            :columns="tableColumns"
            :customRow="customRow"
            class="featureClassification"
            :rowKey="(row, index) => {return index;}"
            :row-selection="{
              columnTitle: ' ',
              selectedRowKeys: selectedRowKeys,
              onChange: radioChange
            }"
            bordered
            :loading="tableLoading"
            size="small"
            :scroll="{ y: 'calc(88vh - 400px)' }"
            :pagination="false">
        </a-table>
      </div>
      <div slot="footer" class="dialog-footer mt10 text-right">
        <a-button @click="closeModal" class="mr20">{{ $t('global-btn.cancel') }}</a-button>
        <a-button
            type="primary"
            :loading="saveLoading"
            @click="save()"
            v-preventReClick>
          {{ $t('global-btn.confirm') }}
        </a-button>
      </div>
    </div>
  </DragModal>
</template>

<script>

import DragModal from "@/components/DragModal";

export default {
  name: "EditModal",
  components: {
    DragModal
  },
  props: {
    showEditModal: {
      type: Boolean,
      default: false
    },
    selectStruIds: {
      type: Array,
      default: []
    }
  },
  watch: {
    showEditModal(val) {
      this.dialogFormVisible = val;
      if (val) {
        this.initData();
      }
    },
  },
  data() {
    return {
      /** 表单布局 */
      formItemLayout: {
        // xxl: '1600px',
        // xl: '1200px',
        // lg: '992px',
        // md: '768px',
        // sm: '576px',
        // xs: '480px',
        labelCol: {
          xxl: { span: 3 },
          xl: { span: 3 },
          lg: { span: 3 },
          md: { span: 24 },
          xs: { span: 24 },
          sm: { span: 24 }
        },
        wrapperCol: {
          xxl: { span: 10 },
          xl: { span: 10 },
          lg: { span: 10 },
          md: { span: 24 },
          xs: { span: 24 },
          sm: { span: 24 }
        }
      },
      /** 模态框状态 */
      dialogFormVisible: false,
      /** 状态字典Dict */
      stateDict: [
        {name: this.$t('global-dict.un-processed'), value: "01"},
        {name: this.$t('global-dict.to-be-decided'), value: "02"},
        {name: this.$t('global-dict.to-be-implemented'), value: "03"},
        {name: this.$t('global-dict.in-working'), value: "10"},
        {name: this.$t('global-dict.complete'), value: "20"},
        {name: this.$t('global-dict.abandon'), value: "04"},
        {name: this.$t('global-dict.finish'), value: "05"},
      ],
      /** 表格数据 */
      tableData: [],
      /** 表格列头 */
      tableColumns: [
        {
          title: () => this.$t('measure-track.measure-track.name'),
          align: "center",
          dataIndex: 'userName',
          ellipsis: true,
        },
        {
          title: () => this.$t('measure-track.measure-track.telephone'),
          align: "center",
          dataIndex: 'telephone',
          ellipsis: true,
        }
      ],
      /** 指定选中项的：key数组 */
      selectedRowKeys: [],
      /** 指定选中项的：数组数据 */
      selectedRow: [],
      /** 规划日期 */
      planDate: undefined,
      /** 状态 */
      state: "",
      /** 负责人 */
      responsible: "",
      /** 表格Loading */
      tableLoading: false,
      /** 保存Loading */
      saveLoading: false,
    }
  },
  methods: {
    /**
     * 关闭模态框
     */
    closeModal() {
      this.$emit("closeEditModal");
      this.$emit("initList");
    },
    /**
     * 初始化数据
     */
    initData() {
      let _that = this;
      _that.tableLoading = true;
      _that.$api.initMeasureTrackEdit({
        fmeaId: _that.$store.getters.rfmeaId,
        lfmeaId: _that.$store.getters.fmeaId,
        selectStruIds: _that.selectStruIds.toString(),
      }).then(res => {
        if (res.flag) {
          _that.tableData = res.data.rdfmPersonModels || [];
          _that.planDate = res.data.planDate;
          _that.state = res.data.state;
          _that.responsible = res.data.responsible;

          // 默认选中
          if (_that.responsible && _that.tableData && _that.tableData.length > 0) {
            for (let i = 0, len = _that.tableData.length; i < len; i++) {
              if (_that.tableData[i].userId === _that.responsible) {
                _that.selectedRowKeys[0] = i;
                _that.selectedRow[0] = _that.tableData[i];
                break;
              }
            }
          }
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
        _that.tableLoading = false;
      });
    },
    /**
     * 校验保存数据
     */
    validateSaveDate() {
      let flag = true;
      if (!this.state) {
        /** 状态不可为空！*/
        this.$message.warning(this.$t('global-message.warn.status-cannot-be-null'), 1);
        return false;
      }
      if (!this.planDate) {
        /** 规划日期不可为空！*/
        this.$message.warning(this.$t('global-message.warn.planning-date-cannot-be-empty'), 1);
        return false;
      }
      return flag;
    },
    /**
     * 保存
     */
    save() {
      let _that = this;
      // 校验
      if (!_that.validateSaveDate()) return;

      _that.saveLoading = true;
      _that.$api.saveMeasureTrackEdit({
        fmeaId: _that.$store.getters.rfmeaId,
        struIds: _that.selectStruIds.toString(),
        state: _that.state,
        planDate: Date.parse(_that.planDate),
        responsible: _that.selectedRow[0] ? _that.selectedRow[0].userId : '',
      }).then(res => {
        if (res.flag) {
          // 操作成功，关闭模态框。
          _that.$message.success(res.message, 1);
          _that.closeModal();
        } else {
          _that.$message.error(res.message, 1);
        }
      }).finally(() => {
        _that.saveLoading = false;
      });
    },
    /**
     * 状态下拉选择事件时
     * @param value
     */
    stateChange(value) {
      this.state = value;
    },
    /**
     * 规划日期选择事件时
     * @param date
     * @param dateString
     */
    planDateChange(date, dateString) {
      this.planDate = date;
    },
    /**
     * 单选框改变事件
     */
    radioChange(rowKeys, row) {
      let lastSelectIndex = rowKeys[rowKeys.length - 1];
      let lastSelectRow = row[row.length - 1];
      this.selectedRowKeys = [lastSelectIndex];
      this.selectedRow[0] = lastSelectRow;
    },
    /**
     * 行点击事件
     */
    customRow(record, index) {
      let _that = this;
      return {
        on: {
          // 鼠标单击行
          click: () => {
            if (_that.selectedRowKeys.indexOf(index) !== -1) {
              _that.selectedRow.splice(_that.selectedRowKeys.indexOf(index), 1);
              _that.selectedRowKeys.splice(_that.selectedRowKeys.indexOf(index), 1);
            } else {
              _that.selectedRowKeys = [index];
              _that.selectedRow[0] = record;
            }
          }
        }
      };
    },
  },
  destroyed() {
    this.closeModal();
  }
};
</script>


<style lang="less" scoped>

/deep/ .ant-table-title {
  color: rgba(0, 0, 0, 0.85);
  font-weight: 700;
}



</style>
