<template>
  <div>
    <!-- 页面主体内容 -->
    <div class="planAddContent">
      <Card style="width:100%" :bordered="false" :dis-hover="true">
        <p slot="title">申购计划详情</p>
        <div slot="extra">
          <Button v-if="form.spzt != '0'" @click="toSpjl">查看审批记录</Button>
          <Button
            @click="addSgjh"
            v-if="form.spzt == '0' && (form.status = '1' || form.status == '2')"
          >保存</Button>
          <Button
            @click="submitSgjh"
            v-if="planType == 'edit' && (form.spzt == '0' || form.spzt == '3')"
          >提交</Button>
          <Button @click="cancel">返回</Button>
        </div>
        <Row class="mainCont">
          <Col span="4" class-name="tables">计划单据号</Col>
          <Col span="4" class-name="tables">
            <span style="color: gray" v-if="form.jhdjh == ''">系统自动生成，不可编辑</span>
            <span v-else>{{ form.jhdjh }}</span>
          </Col>
          <Col span="4" class-name="tables">
            所属区域
            <span class="mustSpan">*</span>
          </Col>
          <Col span="4" class-name="tables">
            <Select
              clearable
              v-model="form.ssqy"
              style="width: 95%"
              @on-change="ssqyChange"
              :disabled="planType == 'edit'"
            >
              <Option
                v-for="item in ssqyList"
                :value="item.areaId + ',' + item.areaName"
                :key="item.areaId"
              >{{ item.areaName }}</Option>
            </Select>
          </Col>
          <Col span="4" class-name="tables">
            所属项目
            <span class="mustSpan">*</span>
          </Col>
          <Col span="4" class-name="tables">
            <Select clearable v-model="form.ssxm" style="width: 95%" :disabled="planType == 'edit'">
              <Option
                v-for="item in ssxmList"
                :value="item.projectId + ',' + item.projectName"
                :key="item.projectId"
              >{{ item.projectName }}</Option>
            </Select>
          </Col>
          <Col span="4" class-name="tables">标题</Col>
          <Col span="4" class-name="tables">
            <span style="color: gray" v-if="form.bt == ''">系统自动生成，不可编辑</span>
            <span v-else>{{ form.bt }}</span>
          </Col>
          <Col span="4" class-name="tables">参考总价（元）</Col>
          <Col span="4" class-name="tables">{{ form.totalPrice }}</Col>
          <Col span="4" class-name="tables">
            计划类型
            <span class="mustSpan">*</span>
          </Col>
          <Col span="4" class-name="tables">
            <Select
              v-model="form.jhlx"
              :disabled="form.spzt == '2' || form.spzt == '1'"
              style="width: 95%"
            >
              <Option
                v-for="item in jhlxList"
                :value="item.value"
                :key="item.value"
              >{{ item.label }}</Option>
            </Select>
          </Col>
          <Col span="4" class-name="tables">
            计划月份
            <span class="mustSpan">*</span>
          </Col>
          <Col span="4" class-name="tables">
            <DatePicker
              :disabled="planType == 'edit'"
              style="width: 95%"
              format="yyyy年MM月"
              :value="form.date"
              @on-change="form.date=$event"
              :options="jhyfOption"
              type="month"
              placeholder="请选择"
            ></DatePicker>
          </Col>
          <Col span="4" class-name="tables">
            分管采购员
            <span class="mustSpan">*</span>
          </Col>
          <Col span="4" class-name="tables">
            <Select
              v-model="form.fgcgy"
              filterable
              :disabled="form.spzt == '2' || form.spzt == '1'"
              style="width: 95%"
            >
              <Option
                v-for="item in cgyList"
                :value="item.userId"
                :key="item.userId"
              >{{ item.userName }}</Option>
            </Select>
          </Col>
          <Col span="4" class-name="tables">申请人</Col>
          <Col span="4" class-name="tables">
            <span>{{ form.sqr }}</span>
          </Col>
          <Col span="4" class-name="tables">审批状态</Col>
          <Col span="4" class-name="tables">
            <span v-if="form.spzt == '0'">未发起</span>
            <span v-if="form.spzt == '1'">审批中</span>
            <span v-if="form.spzt == '2'">审批通过</span>
            <span v-if="form.spzt == '3'">审批不通过</span>
            <span v-if="form.spzt == '4'">审批驳回</span>
          </Col>
          <Col span="4" class-name="tables"></Col>
          <Col span="4" class-name="tables"></Col>
          <Col span="4" class-name="tables"></Col>
          <Col span="4" class-name="tables"></Col>
        </Row>
        <Row class="uplCont" type="flex" justify="center" style="align-items: stretch">
          <Col span="4" class-name="upl">附件</Col>
          <Col span="10" class-name="uplf">
            <Upload
              :headers="uploadHeaders"
              style="width: 80%"
              multiple
              type="drag"
              action="/purchase/common/uploadFile"
              :before-upload="beforeUpload"
              :on-success="uploadFilesSuccess"
              :show-upload-list="false"
              :disabled="form.spzt == '2'  || form.spzt == '1'"
              :on-progress="upFilesLoading"
            >
              <!-- :default-file-list="xzwgForm.filesList" -->
              <div style="padding: 5px 0">
                <Icon type="md-cloud-upload" size="36" style="color: #3399ff"></Icon>
                <span>点击或将文件拖拽到这里上传</span>
              </div>
            </Upload>
          </Col>
          <Col span="10" class="upl" style="padding: 5px">
            <div v-for="(item, index) in form.filesList" :key="index">
              <a
                :href="item.docUrl ? item.docUrl : 'javascript:void(0);'"
                :download="item.fileName"
                :target="item.docUrl ? '_blank' : '_self'"
              >{{ item.fileName }}</a>
              <span
                v-if="form.spzt == '0'  || form.spzt == '3' || form.spzt == '4'"
                style="float: right; cursor:pointer"
                @click="form.filesList.splice(index, 1)"
              >x</span>
            </div>
            <p v-if="uploading" style="text-align: center">上传中...</p>
          </Col>
        </Row>
        <Row class="mainCont">
          <Col span="4" class-name="tables">说明</Col>
          <Col span="20" class-name="tables">
            <Input
              v-model="form.sm"
              :disabled="form.spzt == '2' || form.spzt == '1'"
              placeholder="请输入"
              style="width: 99%"
            />
          </Col>
        </Row>
        <Spin size="large" fix v-if="spinShow"></Spin>
      </Card>
      <Card style="width:100%" :bordered="false" :dis-hover="true">
        <p slot="title">申购计划明细</p>
        <div slot="extra">
          <Button
            v-show="tableData.length"
            type="primary"
            @click="plszOpen"
            :disabled="form.spzt == '2'  || form.spzt == '1'"
          >批量设置</Button>
          <!-- <Button type="primary">批量导入</Button> -->
          <Button
            type="primary"
            @click="addMxShow"
            :disabled="planType == 'add' || form.spzt == '2'  || form.spzt == '1'"
          >新增明细</Button>
        </div>
        <Table
          :columns="tableColumn"
          style="width: 100%"
          :data="tableData"
          :loading="tableLoading"
          @on-select="tableOnSelect"
          @on-select-cancel="tableOnCancel"
          @on-select-all="tableOnSelect"
          @on-select-all-cancel="tableOnCancel"
        >
          <template slot-scope="{ row, index }" slot="amount">
            <div>
              <InputNumber
                :min="1"
                :precision="2"
                v-model="tableData[index].amount"
                :disabled="form.spzt == '2'  || form.spzt == '1'"
                placeholder="请输入"
                style="width: 95%"
              />
            </div>
          </template>
          <template slot-scope="{ row, index }" slot="storehouseId">
            <Select
              :disabled="form.spzt == '2'  || form.spzt == '1'"
              v-model="tableData[index].storehouseId"
              style="width: 95%"
              :transfer="true"
            >
              <Option v-for="item in ckList" :value="item.twId" :key="item.twId">{{ item.twName }}</Option>
            </Select>
          </template>
          <template slot-scope="{ row, index }" slot="linkedPersonName">
            <span>{{ row.linkedPersonName }}</span>
          </template>
          <!-- <template slot-scope="{ row, index }" slot="billType">
            <Select
              :disabled="form.spzt == '2'  || form.spzt == '1'"
              v-model="tableData[index].billType"
              style="width: 95%"
              :transfer="true"
            >
              <Option v-for="item in djList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </template>-->
          <template slot-scope="{ row, index }" slot="referenceTotalPrice">
            <span>{{ (row.amount * row.referencePrice).toFixed(2) }}</span>
          </template>
          <template slot-scope="{ row, index }" slot="arriveTime">
            <DatePicker
              :disabled="form.spzt == '2'  || form.spzt == '1'"
              :transfer="true"
              format="yyyy-MM-dd"
              :options="jhdhsjOption"
              type="date"
              :value="tableData[index].arriveTime"
              @on-change="tableData[index].arriveTime=$event"
              placeholder="请选择"
              style="width: 95%"
            ></DatePicker>
          </template>
          <!-- @on-change="((val, date) => tableDateChange(val, date ,index))" -->
          <template slot-scope="{ row, index }" slot="remark">
            <Input
              :disabled="form.spzt == '2'  || form.spzt == '1'"
              v-model="tableData[index].remark"
              placeholder="请输入"
              style="width: 95%"
            />
          </template>
          <template
            slot-scope="{ row, index }"
            slot="isCancel"
          >{{ row.isCancel == '0' ? '有效' : '已取消' }}</template>
          <template slot-scope="{ row, index }" slot="cz">
            <div
              v-if="form.spzt != '1' && form.spzt !='2' && (form.status = '1' || form.status == '2')"
            >
              <a href="javascript:;" @click="deleteRow(index)">删除</a>
            </div>
            <div v-if="row.isCancel == '0' && form.spzt == '2'">
              <a href="javascript:;" @click="cancelRow(row, index)">取消</a>
            </div>
          </template>
        </Table>
      </Card>
      <Modal v-model="plszShow" title="批量设置" @on-ok="plszOk" @on-cancel="plszCancel">
        <Row class="mainCont">
          <Col span="12" class-name="tables">入库仓库</Col>
          <Col span="12" class-name="tables">
            <Select
              :disabled="form.spzt == '2'  || form.spzt == '1'"
              clearable
              v-model="plrkck"
              style="width: 95%"
              :transfer="true"
            >
              <Option v-for="item in ckList" :value="item.twId" :key="item.twId">{{ item.twName }}</Option>
            </Select>
          </Col>
          <Col span="12" class-name="tables">计划到货时间</Col>
          <Col span="12" class-name="tables">
            <DatePicker
              :disabled="form.spzt == '2'  || form.spzt == '1'"
              :transfer="true"
              format="yyyy-MM-dd"
              type="date"
              :value="pldhsj"
              @on-change="pldhsj=$event"
              :options="jhdhsjOption"
              placeholder="请选择"
              style="width: 95%"
            ></DatePicker>
          </Col>
        </Row>
      </Modal>
    </div>
    <!-- 计划明细新增 -->
    <Modal v-model="contentShow" title="新增申购计划物料" width="1200px">
      <planMxAdd ref="add" @plAdd="plAdd" />
      <div slot="footer">
        <!-- <Button :loading="buttonLoading" @click="addCancel">取消</Button>
        <Button type="primary" :loading="buttonLoading" @click="addOk">确认</Button>-->
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  getProjectList,
  addPurchaseApply,
  queryPurchaseApplyInfo,
  editPurchaseApply,
  warehouseList,
  submitPurchaseApply,
  getLabelByCode4Purchase,
  editPurchaseApplyDetailState
} from "@/service/getData";
import planMxAdd from "./planMxAdd";
export default {
  name: "planAdd",
  components: {
    planMxAdd
  },
  props: ["ssqyList", "cgyList"],
  data() {
    return {
      planMxAddvisible: false,
      id: "",
      spinShow: false,
      contentShow: false,
      requestId: "",
      planType: "add",
      uploadHeaders: {
        token: localStorage.token,
        userId: localStorage.user_id
      },
      jhyfOption: {
        disabledDate(date) {
          let nDate = new Date();
          let dn = +new Date(`${nDate.getFullYear()}-${nDate.getMonth() + 1}`);
          return date.valueOf() < dn;
        }
      },
      jhdhsjOption: {
        disabledDate(date) {
          let nDate = new Date();
          let dn = +new Date(
            `${nDate.getFullYear()}-${nDate.getMonth() + 1}-${nDate.getDate()}`
          );
          return date.valueOf() < dn;
        }
      },
      form: {
        status: "", //申购计划状态
        jhdjh: "", // 计划单据号
        bt: "", //标题
        spzt: 0, //审批状态
        date: "", //计划月份
        ssqy: "", //所属区域
        ssxm: "", //所属项目
        jhlx: "", //计划类型
        fgcgy: "", //分管采购员
        totalPrice: 0, //总价
        sqr: localStorage.user_name, //申请人
        filesList: []
      },
      // ssqyList: [{ label: "test", value: "1" }],
      ssxmList: [],
      jhlxList: [
        { label: "计划性申购", value: 1 },
        { label: "临时申购", value: 2 }
      ],
      sqrList: [],
      uploading: false,
      // 批量设置
      plszShow: false,
      plrkck: "",
      pldhsj: "",
      // table
      ckList: [],
      djList: [],
      tableColumn: [
        {
          type: "selection",
          width: 60,
          align: "center"
        },
        {
          title: "物料编码",
          key: "code",
          tooltip: "true",
          width: 100
        },
        {
          title: "物料分类",
          key: "firstClassName",
          tooltip: "true",
          width: 100
        },
        {
          title: "物料名称",
          key: "materialName",
          tooltip: "true",
          width: 100
        },
        {
          title: "规格型号",
          key: "specs",
          tooltip: "true",
          width: 100
        },
        {
          title: "单位",
          key: "unit",
          tooltip: "true",
          width: 100
        },
        {
          title: "库存量",
          key: "inventory",
          tooltip: "true",
          width: 100
        },
        {
          title: "申购数量",
          slot: "amount",
          tooltip: "true",
          width: 100
        },
        {
          title: "参考单价（元）",
          key: "referencePrice",
          tooltip: "true",
          width: 120
        },
        {
          title: "参考总价（元）",
          slot: "referenceTotalPrice",
          tooltip: "true",
          width: 120
        },
        {
          title: "入库仓库",
          slot: "storehouseId",
          tooltip: "true",
          width: 100
        },
        {
          title: "对接人",
          slot: "linkedPersonName",
          tooltip: "true",
          width: 100
        },
        // {
        //   title: "单据类型",
        //   slot: "billType",
        //   tooltip: "true",
        //   width: 100
        // },
        {
          title: "计划到货时间",
          slot: "arriveTime",
          tooltip: "true",
          width: 130
        },
        {
          title: "备注",
          slot: "remark",
          tooltip: "true",
          width: 150
        },
        // {
        //   title: "状态",
        //   slot: "isCancel",
        //   tooltip: "true",
        //   width: 100
        // },
        {
          title: "操作",
          slot: "cz",
          tooltip: "true",
          width: 60
        }
      ],
      tableData: [],
      tableSelect: [],
      tableLoading: false
    };
  },
  created() {
    // getLabelByCode4Purchase({ dictCode: "billType" }).then(res => {
    //   if (res.status == 200) {
    //     this.djList = res.data;
    //   } else {
    //     this.$Message.error(res.message);
    //   }
    // });
  },
  methods: {
    //批量设置弹窗
    plszOpen() {
      if (!this.tableSelect.length) {
        this.$Message.error("请至少选择一条物料明细！");
        return false;
      } else {
        this.plszShow = true;
      }
    },
    plszOk() {
      let ck = this.plrkck ? this.plrkck : "";
      let sj = this.pldhsj ? this.pldhsj : "";
      let select = this.tableSelect;
      for (let item in this.tableData) {
        let id = this.tableData[item].id;
        if (select.filter(a => a.id == id).length > 0) {
          if (ck != "") {
            this.tableData[item].storehouseId = ck;
          }
          if (sj != "") {
            this.tableData[item].arriveTime = sj;
          }
        }
      }
    },
    plszCancel() {},
    //表单上传
    beforeUpload() {},
    upFilesLoading() {
      this.uploading = true;
    },
    uploadFilesSuccess(response, file, fileList) {
      this.uploading = false;
      this.form.filesList.push({
        fileName: response.data.fileName,
        filePath: response.data.filePath,
        fileDetailType: ""
      });
    },
    plAdd(list) {
      this.contentShow = false;
      for (let item in list) {
        if (
          this.tableData.filter(a => a.materialId == list[item].materialId)
            .length > 0
        ) {
        } else {
          this.tableData.push(list[item]);
        }
      }
    },
    //查询申购计划详情
    getSgjh(id, arr) {
      this.id = id;
      let postData = {
        id: id
      };
      this.spinShow = true;
      queryPurchaseApplyInfo(postData).then(res => {
        this.spinShow = false;
        if (res.status == 200) {
          this.form.jhdjh = res.data.code;
          this.form.bt = res.data.title;
          this.form.ssqy = `${res.data.areaId},${res.data.areaName}`;
          this.form.ssxm = `${res.data.projectId},${res.data.projectName}`;
          this.form.jhlx = res.data.type;
          this.form.date = res.data.applyMonth;
          // this.form.fgcgy = res.data.purchaserName;
          this.form.sqr = res.data.applicantName;
          this.form.spzt = res.data.applyStatus;
          if (res.data.applyStatus == "2") {
            this.tableColumn = [
              {
                type: "selection",
                width: 60,
                align: "center"
              },
              {
                title: "物料编码",
                key: "code",
                tooltip: "true",
                width: 100
              },
              {
                title: "物料分类",
                key: "firstClassName",
                tooltip: "true",
                width: 100
              },
              {
                title: "物料名称",
                key: "materialName",
                tooltip: "true",
                width: 100
              },
              {
                title: "规格型号",
                key: "specs",
                tooltip: "true",
                width: 100
              },
              {
                title: "单位",
                key: "unit",
                tooltip: "true",
                width: 100
              },
              {
                title: "库存量",
                key: "inventory",
                tooltip: "true",
                width: 100
              },
              {
                title: "申购数量",
                slot: "amount",
                tooltip: "true",
                width: 100
              },
              {
                title: "参考单价（元）",
                key: "referencePrice",
                tooltip: "true",
                width: 120
              },
              {
                title: "参考总价（元）",
                slot: "referenceTotalPrice",
                tooltip: "true",
                width: 120
              },
              {
                title: "入库仓库",
                slot: "storehouseId",
                tooltip: "true",
                width: 100
              },
              {
                title: "对接人",
                slot: "linkedPersonName",
                tooltip: "true",
                width: 100
              },
              // {
              //   title: "单据类型",
              //   slot: "billType",
              //   tooltip: "true",
              //   width: 100
              // },
              {
                title: "计划到货时间",
                slot: "arriveTime",
                tooltip: "true",
                width: 130
              },
              {
                title: "备注",
                slot: "remark",
                tooltip: "true",
                width: 150
              },
              {
                title: "状态",
                slot: "isCancel",
                tooltip: "true",
                width: 100
              },
              {
                title: "操作",
                slot: "cz",
                tooltip: "true",
                width: 60
              }
            ];
          }
          this.form.status = res.data.status;
          this.form.fgcgy = `${res.data.purchaserId}`;
          this.form.ylh = res.data.gpUnionpayNo;
          this.form.sf = res.data.gpProvince;
          this.form.yb = res.data.gpPostalCode;
          this.form.email = res.data.gpEmail;
          this.form.fax = res.data.gpFax;
          this.form.filesList = res.data.attachmentList;
          this.form.sm = res.data.remark;
          this.requestId = res.data.requestId;
          let postData = {
            areaId: this.form.ssqy.split(",")[0],
            userId: localStorage.user_id
          };
          getProjectList(postData).then(res => {
            this.ssxmList = res.items;
          });
          let getData = {
            areaId: res.data.areaId,
            projectId: res.data.projectId
          };
          warehouseList(getData).then(res => {
            if (res.status == 200) {
              for (let i in res.data) {
                res.data[i].twId = res.data[i].twId;
              }
              this.ckList = res.data;
            }
          });
          if (arr) {
            this.tableData = arr;
          } else {
            this.tableData = res.data.detailList;
          }
        }
      });
    },
    //新增申购计划
    addSgjh() {
      let mustArr = ["ssqy", "ssxm", "jhlx", "date", "fgcgy"];
      for (let i in mustArr) {
        if (!this.form[mustArr[i]]) {
          this.$Message.error("请将信息填写完整！");
          return false;
        }
        if (this.form[mustArr[i]] == "" || this.form[mustArr[i]].length == 0) {
          this.$Message.error("请将信息填写完整！");
          return false;
        }
      }
      if (this.planType == "add") {
        let postData = {
          areaId: this.form.ssqy.split(",")[0],
          areaName: this.form.ssqy.split(",")[1],
          projectId: this.form.ssxm.split(",")[0],
          projectName: this.form.ssxm.split(",")[1],
          type: this.form.jhlx,
          applyMonth: this.form.date,
          purchaserId: this.form.fgcgy,
          purchaserName:
            this.form.fgcgy == ""
              ? ""
              : this.cgyList.filter(a => a.userId == this.form.fgcgy)[0]
                  .userName,
          applicantId: localStorage.user_id,
          applicantName: localStorage.user_name,
          attachmentList: this.form.filesList,
          remark: this.form.sm
        };
        this.spinShow = true;
        addPurchaseApply(postData).then(res => {
          this.spinShow = false;
          if (res.status == 200) {
            this.$Message.success("新建申购计划成功！");
            this.form.bt = res.data.title;
            this.form.jhdjh = res.data.code;
            this.form.filesList = res.data.attachmentList;
            this.id = res.data.id;
            this.planType = "edit";
            let getData = {
              areaId: res.data.areaId,
              projectId: res.data.projectId
            };
            warehouseList(getData).then(res => {
              if (res.status == 200) {
                this.ckList = res.data;
              }
            });
          } else {
            this.$Message.error(res.message);
          }
        });
      } else {
        this.editSgjh();
      }
    },
    editSgjh() {
      for (let i in this.tableData) {
        if (this.tableData[i].storehouseId == "") {
          this.$Message.error("请选择计划明细仓库！");
          return false;
        }
        if (this.tableData[i].amount <= 0) {
          this.$Message.error("计划明细申购数量不能小于或等于0！");
          return false;
        }
        // if (this.tableData[i].billType == "") {
        //   this.$Message.error("请选择计划明细单据类型！");
        //   return false;
        // }
        this.tableData[i].referenceTotalPrice = (
          this.tableData[i].amount * this.tableData[i].referencePrice
        ).toFixed(2);
        this.tableData[i].storehouseName = this.ckList.filter(
          a => a.twId == this.tableData[i].storehouseId
        )[0].twName;
      }
      // for (let i in this.tableData) {
      //   this.tableData[i].amount = Number(this.tableData[i].amount).toFixed(2);
      // }
      let postData = {
        areaId: this.form.ssqy.split(",")[0],
        areaName: this.form.ssqy.split(",")[1],
        projectId: this.form.ssxm.split(",")[0],
        projectName: this.form.ssxm.split(",")[1],
        type: this.form.jhlx,
        applyMonth: this.form.date,
        purchaserId: this.form.fgcgy,
        purchaserName:
          this.form.fgcgy == ""
            ? ""
            : this.cgyList.filter(a => a.userId == this.form.fgcgy)[0].userName,
        applicantId: localStorage.user_id,
        applicantName: localStorage.user_name,
        attachmentList: this.form.filesList,
        remark: this.form.sm,
        id: this.id,
        detailList: this.tableData
      };
      this.spinShow = true;
      return new Promise((resolve, reject) => {
        editPurchaseApply(postData).then(res => {
          this.spinShow = false;
          if (res.status == 200) {
            this.$Message.success("编辑申购计划成功！");
            this.getSgjh(this.id);
            resolve();
            // this.cancel();
          } else {
            this.$Message.error(res.message);
            reject();
          }
        });
      });
    },
    tableOnSelect(selection, row) {
      this.tableSelect = selection;
    },
    tableOnCancel(selection, row) {
      this.tableSelect = selection;
    },
    //审批记录跳转
    toSpjl() {
      let link = `http://gdoa1.kingser.com:88/westvalley/PSWorkflow/PSWorkflowDecode.jsp?loginmsg=bG9naW5pZD1wbXMmdXNlcnBhc3N3b3JkPVBBYjEyMzQ1Nio=&requestid=${this.requestId}`;
      window.open(link);
    },
    submitSgjh() {
      let cango = true;
      for (let i in this.tableData) {
        if (this.tableData[i].storehouseId == "") {
          cango = false;
          this.$Message.error("请选择计划明细仓库！");
          return false;
        }
        this.tableData[i].referenceTotalPrice = (
          this.tableData[i].amount * this.tableData[i].referencePrice
        ).toFixed(2);
        this.tableData[i].storehouseName = this.ckList.filter(
          a => a.twId == this.tableData[i].storehouseId
        )[0].twName;
      }
      if (!cango) {
        return false;
      }
      this.spinShow = true;
      this.editSgjh().then(() => {
        console.log(123);
        let postData = {
          id: this.id
        };
        submitPurchaseApply(postData).then(res => {
          this.spinShow = false;
          if (res.status == 200) {
            this.$Message.success("提交申购计划成功！");
            this.form.spzt = "1";
          } else {
            this.$Message.error(res.message);
          }
        });
      });
    },
    //所属区域切换
    ssqyChange(val) {
      if (this.form.ssqy) {
        let postData = {
          areaId: this.form.ssqy.split(",")[0],
          userId: localStorage.user_id
        };
        getProjectList(postData).then(res => {
          this.form.ssxm = "";
          this.ssxmList = res.items;
        });
      }
    },
    deleteRow(index) {
      this.tableData.splice(index, 1);
    },
    cancelRow(row, index) {
      if (this.form.sqr != localStorage.user_name) {
        this.$Message.error("非计划申请人不允许取消申购计划明细！");
        return false;
      }
      editPurchaseApplyDetailState(row.id).then(res => {
        if (res.status == 200) {
          this.$Message.success("取消申购计划明细成功！");
          this.tableData[index].isCancel = 1;
        } else {
          this.$Message.error(res.message);
        }
      });
    },
    //明细弹窗
    addMxShow() {
      this.contentShow = true;
      this.$refs.add.projectId = this.form.ssxm;
      this.$refs.add.documentNo = this.form.jhdjh;
      this.$refs.add.getTableData();
    },
    //返回、取消
    cancel() {
      this.form = {
        jhdjh: "", // 计划单据号
        bt: "", //标题
        spzt: 0, //审批状态
        date: "", //计划月份
        ssqy: "", //所属区域
        ssxm: "", //所属项目
        jhlx: "", //计划类型
        fgcgy: "", //分管采购员
        totalPrice: 0, //总价
        sqr: localStorage.user_name, //申请人
        filesList: []
      };
      this.tableColumn = [
        {
          type: "selection",
          width: 60,
          align: "center"
        },
        {
          title: "物料编码",
          key: "code",
          tooltip: "true",
          width: 100
        },
        {
          title: "物料分类",
          key: "firstClassName",
          tooltip: "true",
          width: 100
        },
        {
          title: "物料名称",
          key: "materialName",
          tooltip: "true",
          width: 100
        },
        {
          title: "规格型号",
          key: "specs",
          tooltip: "true",
          width: 100
        },
        {
          title: "单位",
          key: "unit",
          tooltip: "true",
          width: 100
        },
        {
          title: "库存量",
          key: "inventory",
          tooltip: "true",
          width: 100
        },
        {
          title: "申购数量",
          slot: "amount",
          tooltip: "true",
          width: 100
        },
        {
          title: "参考单价（元）",
          key: "referencePrice",
          tooltip: "true",
          width: 120
        },
        {
          title: "参考总价（元）",
          slot: "referenceTotalPrice",
          tooltip: "true",
          width: 120
        },
        {
          title: "入库仓库",
          slot: "storehouseId",
          tooltip: "true",
          width: 100
        },
        {
          title: "对接人",
          slot: "linkedPersonName",
          tooltip: "true",
          width: 100
        },
        // {
        //   title: "单据类型",
        //   slot: "billType",
        //   tooltip: "true",
        //   width: 100
        // },
        {
          title: "计划到货时间",
          slot: "arriveTime",
          tooltip: "true",
          width: 130
        },
        {
          title: "备注",
          slot: "remark",
          tooltip: "true",
          width: 150
        },
        {
          title: "操作",
          slot: "cz",
          tooltip: "true",
          width: 60
        }
      ];
      this.id = "";
      this.tableData = [];
      this.tableSelect = [];
      this.planType = "add";
      this.spinShow = false;
      this.$emit("return");
    }
  },
  watch: {
    ssqyList(val) {
      if (val && val.length && val.length === 1) {
        const [{ areaId, areaName }] = val;
        this.form.ssqy = `${areaId},${areaName}`;
        this.ssqyChange();
      }
    },
    ssxmList(val) {
      if (val && val.length && val.length === 1) {
        console.log("change");
        const [{ projectId, projectName }] = val;
        this.form.ssxm = `${projectId},${projectName}`;
      }
    },
    tableData: {
      handler(val, name) {
        // console.log(val, 11111111111111111);
        let total = 0;
        let str = "";
        for (let item in val) {
          if (val[item].isCancel) {
          } else {
            total += val[item].referencePrice * val[item].amount;
          }
        }
        this.form.totalPrice = Number(total).toFixed(2);
      },
      deep: true
    }
  }
};
</script>

<style lang="scss" scoped>
.mustSpan {
  color: red;
  margin-left: 2px;
}
button {
  min-width: 80px;
}
.uplCont {
  border-left: 1px solid #e4e4e4;
  .upl {
    flex: auto;
    border-right: 1px solid #e4e4e4;
    &:nth-child(1) {
      background: #f8f9fb;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  .uplf {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 80px;
  }
}
.mainCont .tables {
  height: 50px;
  border-right: 1px solid #e4e4e4;
  border-bottom: 1px solid #e4e4e4;
  display: flex;
  align-items: center;
  justify-content: center;
  word-break: break-all;
  &:nth-child(2n + 1) {
    background: #f8f9fb;
  }
}
.mainCont {
  border-left: 1px solid #e4e4e4;
  border-top: 1px solid #e4e4e4;
}
ivu-card-head-inner,
.ivu-card-head p {
  display: inline-block;
  width: 100%;
  height: 20px;
  line-height: 20px;
  font-size: 14px;
  color: #17233d;
  font-weight: 700;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-weight: normal;
}
</style>